package com.itsu.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.itsu.entity.User;
import com.itsu.mapper.UserMapper;

@RestController
public class MyController {

	@Resource
	private UserMapper userMapper;

	@GetMapping("/users")
	@Cacheable(value = "users")
	public List<User> getUsers() {
		return userMapper.selectList(null);
	}

	@GetMapping("/user/{id}")
	@Cacheable(value = "user", key = "#id", unless = "#result==null")
	public User getUser(@PathVariable("id") long id) {
		return userMapper.selectById(id);
	}

	@GetMapping("/user/update/{id}")
	@Caching(put = { @CachePut(value = "user", key = "#id",unless = "#result==null") }, evict = {
			@CacheEvict(value = "users", allEntries = true) })
	public User updateUser(@PathVariable("id") long id) {
		User user = userMapper.selectById(id);
		user.setName(user.getName() + " updated");
		userMapper.updateById(user);
		return user;
	}

	@GetMapping("/user/delete/{id}")
	@Caching(evict = { @CacheEvict(value = "user", key = "#id"), @CacheEvict(value = "users", allEntries = true) })
	public String deleteUser(@PathVariable("id") long id) {
		return userMapper.deleteById(id) + "";
	}

	@GetMapping("/user/add")
	@CacheEvict(value = "users", allEntries = true)
	public String add(User user) {
		return userMapper.insert(user) + "";
	}

}
